import os
import re
import sys

def rename_leetcode_files(folder_path):
    # 遍历文件夹内所有文件
    for filename in os.listdir(folder_path):
        # 检查是否为.java文件且符合Leetcode+数字模式
        if re.match(r'(?i)^leetcode(\d+)\.java$', filename):
            # 提取数字部分（如Leetcode1.java → 1）
            match = re.fullmatch(r'(?i)leetcode(\d+)\.java', filename)
            number = match.group(1)

            # 新文件名：LeetCode + 数字 + .java
            new_filename = f"LeetCode{number}.java"

            # 旧文件绝对路径
            old_path = os.path.join(folder_path, filename)
            new_path = os.path.join(folder_path, new_filename)

            # 重命名文件（如果新旧名称不同）
            if filename != new_filename:
                os.rename(old_path, new_path)
                print(f"重命名文件: {filename} → {new_filename}")

            # 更新文件内的类名
            with open(new_path, 'r+', encoding='utf-8') as f:
                content = f.read()
                # 替换类声明（如class Leetcode1 → class LeetCode1）
                new_content = re.sub(
                    r'(?i)(class\s+)Leetcode(\d+)',
                    lambda m: f"{m.group(1)}LeetCode{m.group(2)}",
                    content
                )
                # 写回文件
                f.seek(0)
                f.truncate()
                f.write(new_content)
                print(f"更新类名: LeetCode{number}")

if __name__ == "__main__":
    # if len(sys.argv) < 2:
    #     print("请指定文件夹路径，例如: python rename.py /path/to/java/files")
    #     sys.exit(1)

    folder_path = 'D:/project/algorithm-training/src/com/wlr/study/leetcode'
    rename_leetcode_files(folder_path)